/*
 * fonte: http://victorserta.com.br/blog/2008/12/11/programacao-concorrente-com-javautilconcurrent-parte-1/
 */

package server.thread;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Level;
import server.piles.Piles;

/**
 *
 * @author Sérgio C. Peres
 */
public class HTTPReply implements Runnable{
    
    private HTTPServerPool httpServer;
    private Socket socket;
    
    public HTTPReply(HTTPServerPool httpServer, Socket socket) {
        this.httpServer = httpServer;
        this.socket = socket;
    }
    
    @Override
    public void run() {
        file();
        
//        HTTPPostAttend p = new HTTPPostAttend(httpServer,socket);
//        p.file();
        
        
//        new HTTPFile(socket).postFile();
    }
    
    private void file() {
        InetAddress infoCliente;
        HTTPResponse res;
        
        InputStream input = null;
        OutputStream output = null;
        
        try {
            infoCliente = socket.getInetAddress();
            //System.out.println("\nCliente: " + infoCliente.getHostName() + " conectou ao servidor!");
            
            input = socket.getInputStream();
            output = socket.getOutputStream();
            
            String requestString = convertStreamToString(input);
            System.out.println("Conexão recebida. Conteúdo:\n" + requestString);
            Request request = new Request();
            request.parse(requestString);
            
            res = new HTTPResponse(httpServer, new DataOutputStream(output));
            if (res.setRequest(request.getMethod(),request.getUri()))
            {
                res.sendResponse(request,httpServer.getPilha());
            }
            input.close();
            output.close();
        } catch (java.io.IOException ex) {
            System.out.println("Erro de Conexão: " + ex.getMessage());
        } finally {
            try {
                socket.close();
            } catch (java.io.IOException ex) {
                System.out.println("Erro ao tetar enserar um socket da thread....\n Erro: " + ex.getMessage());
            }
        }
    }
    
    private void imagem() {
        InputStream in;  
        try {
            in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in);  
            BufferedReader reader = new BufferedReader(isr); 
            
            InputStream input = socket.getInputStream();
            String requestString = convertStreamToString(input);
            System.out.println("Conexão recebida. Conteúdo:\n" + requestString);
            Request request = new Request();
            request.parse(requestString);
            
            String fName = reader.readLine();  
            System.out.println(fName);  
            File f1 = new File("www\\" + request.getUri().substring(1));  
            FileOutputStream out = new FileOutputStream(f1);  
            int c;  
            while ((c = in.read()) != -1) {  
                out.write(c);  
            }
        } catch (IOException ex) {
            System.out.println("Erro com imagem()\n"+ex.getMessage());
        }
    }
    
    private String convertStreamToString(InputStream is) {

        if (is != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[2048];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is));
                int i = reader.read(buffer);
                writer.write(buffer, 0, i);
            } catch (IOException e) {
                System.out.println(Level.SEVERE + "\n\tErro ao converter stream para string \n" + e);
                return "";
            }
            return writer.toString();
        } else {
            return "";
        }
    }
}
